const express = require("express");
const db = require("../model/db");

const router = express.Router();
// 同步的查询语句
async function awaitSql(q) {
  const data = await new Promise((resolve, reject) => {
    db.query(q, function (err, data) {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
  return data;
}
// 订单状态 列表
router.get("/orderStateList", async (req, res) => {
  db.query("SELECT * FROM orderState", function (err, data) {
    if (err) throw err;
    res.send({
      data,
      msg: 200
    });
  });
})
// 订单来源 列表
router.get("/orderSourceList", async (req, res) => {
  db.query("SELECT * FROM orderSource", function (err, data) {
    if (err) throw err;
    res.send({
      data,
      msg: 200
    });
  });
})
// 门店信息 列表
router.get("/storeList", async (req, res) => {
  db.query("SELECT * FROM store", function (err, data) {
    if (err) throw err;
    res.send({
      data,
      msg: 200
    });
  });
})
// 用户信息 列表
router.get("/userList", async (req, res) => {
  db.query("SELECT * FROM custom", function (err, data) {
    if (err) throw err;
    res.send({
      data,
      msg: 200
    });
  });
})
// 车辆信息 列表
router.get("/vehicleList", async (req, res) => {
  db.query("SELECT * FROM vehicle", function (err, data) {
    if (err) throw err;
    res.send({
      data,
      msg: 200
    });
  });
})
// 订单创建  未完成
router.get("/createOrder", async (req, res) => {
  const body = {
    "mid": 3,
    "returnAddress": 3,
    "collectionTime": "2024-01-23",
    "returnTime": "2024-01-22",
    "collectionAddress": 2,
    "orderSource": 4,
    "uid": 5,
    "notes": ''
  }
  const { mid, returnAddress, collectionTime, returnTime, collectionAddress, orderSource, uid, notes } = body;
  // const { mid, returnAddress, collectionTime, returnTime, collectionAddress, orderSource, uid, notes } = req.body;
  body.createTime = new Date()
  const createTime = body.createTime.toISOString().slice(0, 10).replace(/-/g, ''); // 2
  let lists = await awaitSql(`SELECT * FROM ${'`'}order${'`'} WHERE oid LIKE '%${createTime}%'`)
  console.log(lists.length > 0);
  let oid = lists.length > 100 ? lists.length : lists.length > 10 ? '0' + lists.length : lists.length > 0 ? '00' + lists.length : '001'
  body.oid = createTime + oid;

  // const sql = `INSERT INTO orders (oid,  vCode, username, createTime, state, source) VALUES ('${oid}', '${type}', '${vCode}', '${username}', '${createTime}', '${state}', '${source}')`;
  // await awaitSql(sql);
  res.json({ message: "订单创建成功" });
})
// 订单列表 多条件查询
router.get("/orderList", async (req, res) => {
  const { oid, type, vCode, username, createTime, state, source } = req.query;
  console.log(oid, type, vCode, username, createTime, state, source);
  const whereList = []
  if (oid) {
    whereList.push(`oid LIKE '%${oid}%'`)
  }
  if (type) {
    let mid = await awaitSql(`select * from vehicle where vname = '${type}'`)
    let ids = mid.map(item => {
      return item.id
    })
    whereList.push(`mid IN (${ids.join(',')})`)
  }
  if (vCode) {
    let mid = await awaitSql(`select * from vehicle where platenumber LIKE '%${vCode}%'`)
    let ids = mid.map(item => { return item.id })
    whereList.push(`mid IN (${ids.join(',')})`)
  }
  if (username) {
    let uid = await awaitSql(`select * from Users where name LIKE '%${username}%'`)
    let ids = uid.map(item => { return item.id })
    whereList.push(`uid IN (${ids.join(',')})`)
  }
  if (createTime) {
    whereList.push(`createTime BETWEEN '${createTime.slice(',')[0]}' AND '${createTime.slice(',')[1]}'`)
  }
  if (state) {
    whereList.push(`state = ${state}`)
  }
  if (source) {
    whereList.push(`orderSource = ${source}`)
  }
  let q = 'select * from `order`'
  if (whereList.length > 0) {
    q += ' where ' + whereList.join(' AND ')
  }
  console.log(q);
  db.query(q, async (err, data) => {

    if (err) err;
    const users = await awaitSql(`select * from custom`)
    const midlist = await awaitSql(`select * from vehiclemodel`)
    const stateList = await awaitSql(`select * from orderState`)
    const address = await awaitSql(`select * from store`)
    // console.log(user);
    const orderList = data.map(item => {
      const user = users.find(it => it.id === item.uid)
      const mid = midlist.find(it => it.cid === item.mid)
      const state = stateList.find(it => it.id === item.state)
      const coll = address.find(it => it.id === item.collectionAddress)
      const retu = address.find(it => it.id === item.returnAddress)
      console.log(item);
      return {
        key: item.id,
        createTime: {
          date: item.createTime,
          orderId: item.oid
        },
        uid: {
          name: user.name,
          phone: user.tell
        },
        collection_return_time: {
          collectionTime: item.collectionTime,
          returnTime: item.returnTime,
        },
        collection_return_address: {
          collectionAddress: coll.address + '/' + coll.detaile, // 取车地址
          returnAddress: retu.address + '/' + retu.detaile, // 还车地址
        }, // 取还车地址
        leaseTime: item.leaseTime, // 租期
        mid: {
          id: item.mid, // 车型id
          name: `${mid.brand}/${mid.cxname}/${mid.TransmissionType}/${mid.seats}`, // 车型名称
        }, // 车型id
        rent: item.rent, // 支付金额
        deposit: item.deposit, // 押金金额
        state: {
          id: state.id, // 订单状态id
          name: state.name, // 订单状态名称
          state: state.state, // 订单状态 1进行中 0已取消或逾期
        }, // 订单状态
      }
    })
    res.send({
      orderList,
      msg: 200
    });
  });
});
// 系统设置 列表
router.get('/settingsList', async (req, res) => {
  let id = req.query.id || '0'
  let q = 'select * from settings'
  if (id !== '0') {
    q += ` where uid = ${id}`
  }
  console.log(q);
  let data = await Promise.all([awaitSql(q), awaitSql('select * from insureremind',), awaitSql('select * from annuallyremind',), awaitSql('select * from maintenanceremind',)])
  res.send({
    data: data[0],
    insureRemind: data[1],
    annuallyRemind: data[2],
    maintenanceRemind: data[3],
    msg: 200
  });
})
// 系统设置 修改
router.post('/updSettings', (req, res) => {
  let body = req.body
  db.query(`update settings set ${body.type} = ${body.value} where id = ${body.id}`, (err, data) => {
    if (err) err;
    res.send({ msg: 200 });
  })
})
module.exports = router;
